package com.fesine.learn.controller;

import com.fesine.commons.util.CryptographyUtil;
import com.fesine.commons.util.DateUtils;
import com.fesine.commons.util.GenerateUUID;
import com.fesine.commons.util.ResponseUtils;
import com.fesine.learn.po.UserInfoPo;
import com.fesine.learn.service.UserInfoService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by Administrator on 2017/4/13.
 */
@Controller
@RequestMapping("/userInfo")
public class UserInfoController {
    private static final Logger logger=Logger.getLogger(UserInfoController.class);

    @Resource
    private UserInfoService userInfoService;

    public static long initTime;
    public static long loginTime;

    @Value("${upload.file.root}")
    private String uploadFileRoot;

    /**
     * 登录操作
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public void login(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map=new HashMap<String,Object>();
        loginTime=System.currentTimeMillis();
        if (loginTime-initTime>30000){
            map.put("success",false);
            map.put("msg","验证码过期，有效时间30秒！");
        }else{
            String userName=request.getParameter("userName");
            String captchaToken=request.getSession().getAttribute("captchaToken")
                    .toString().toLowerCase();
            String checkCode=request.getParameter("checkCode").toLowerCase();
            logger.info("----------->captchaToken:"+captchaToken+",checkCode:"+checkCode);
            //全部转为小写 不用区分
            if (!captchaToken.equals(checkCode)){
                map.put("success",false);
                map.put("msg","验证码错误");
            }else{
                UserInfoPo userInfoPo=new UserInfoPo();
                userInfoPo.setUserName(userName);
                userInfoPo=userInfoService.getUserInfo(userInfoPo);
                if (userInfoPo!=null){
                    //有该用户 验证密码
                    String password=request.getParameter("password");
                    if(CryptographyUtil.md5(password,"fesine")
                            .equals(userInfoPo.getPassword())){
                        request.getSession().setAttribute("userName",userName);
                        request.getSession().setAttribute("nickName",userInfoPo.getNickName());
                        request.getSession().setAttribute("uploadFileRoot",uploadFileRoot);
                        map.put("success",true);
                        map.put("msg","验证成功！");
                    }else{
                        map.put("success",false);
                        map.put("msg","密码错误！");
                    }
                }else{
                    map.put("success",false);
                    map.put("msg","用户不存在！");
                }
            }
        }
        try {
            ResponseUtils.outPut(response,map);
        } catch (Exception e) {
            logger.error("",e);
        }

    }


    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request,HttpServletResponse response) throws Exception{
        request.getSession().invalidate();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("success",true);
        map.put("msg","注销成功！");
        try {
            ResponseUtils.outPut(response,map);
        } catch (Exception e) {
            logger.error("",e);
        }

    }


    /**
     * 添加用户信息
     */
    @RequestMapping(value = "/addUserInfo",method = RequestMethod.POST)
    public void addUserInfo(@RequestParam MultipartFile photos,
                            HttpServletRequest request, HttpServletResponse response) throws Exception{
        UserInfoPo u=createUserInfo(request);
        u.setId(GenerateUUID.getUUId());
        Date date=new Date();
        u.setCreateTime(date);
        u.setUpdateTime(date);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("success",true);
        map.put("msg","添加用户信息成功！");
        try {
            if (photos.isEmpty()){
                logger.info("------->没有上传头像");
                u.setHeadPhoto("default.jpg");
            }else{
                String headPhoto=uploadPhotos(photos,request);
                u.setHeadPhoto(headPhoto);
            }
            userInfoService.addUserInfo(u);
        } catch (IOException e) {
            logger.error("",e);
            map.put("success",false);
            map.put("msg","添加用户信息失败！");
        }
        try {
            ResponseUtils.outPut(response,map);
        } catch (Exception e) {
            logger.error("",e);
        }

    }

    /**
     * 修改用户信息
     */
    @RequestMapping(value = "/updateUserInfo",method = RequestMethod.POST)
    public void updateUserInfo(@RequestParam MultipartFile photos
            ,HttpServletRequest request,HttpServletResponse response){
        UserInfoPo u=createUserInfo(request);
        Date date=new Date();
        u.setUpdateTime(date);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("success",true);
        map.put("msg","修改用户信息成功！");
        try {
            if (!photos.isEmpty()){
                String headPhoto=uploadPhotos(photos,request);
                u.setHeadPhoto(headPhoto);
            }
            userInfoService.modifyUserInfo(u);
        } catch (IOException e) {
            logger.error("",e);
            map.put("success",false);
            map.put("msg","修改用户信息失败！");
        }
        try {
            ResponseUtils.outPut(response,map);
        } catch (Exception e) {
            logger.error("",e);
        }
    }

    /**
     * 修改用户登录密码
     */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST)
    public void updatePassword(HttpServletRequest request,HttpServletResponse response){
        UserInfoPo u=createUserInfo(request);
        Date date=new Date();
        u.setUpdateTime(date);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("success",true);
        map.put("msg","修改用户密码成功！");
        try {
            userInfoService.modifyUserInfo(u);
        } catch (Exception e) {
            logger.error("",e);
            map.put("success",false);
            map.put("msg","修改用户密码失败！");
        }
        try {
            ResponseUtils.outPut(response,map);
        } catch (Exception e) {
            logger.error("",e);
        }
    }

    /**
     * 文件上传
     */
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    public void uploadFile(@RequestParam MultipartFile file
            ,HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("success",true);
        map.put("msg","文件上传成功！");
        try {
            String fileName=uploadPhotos(file,request);
            map.put("fileName",fileName);
        } catch (IOException e) {
            logger.error("",e);
            map.put("success",false);
            map.put("msg","文件上传失败！");
        }
        try {
            ResponseUtils.outPut(response,map);
        } catch (Exception e) {
            logger.error("",e);
        }
    }

    /**
     * 删除用户信息
     */
    @RequestMapping(value = "deleteUserInfo",method = RequestMethod.POST)
    public void deleteUserInfo(HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> map=new HashMap<String,Object>();
        String userIds=request.getParameter("userIds").replace("\"","");
        String[] idsArr=userIds.split(",");
        map.put("success",true);
        map.put("msg","删除用户成功！");
        try {
            userInfoService.deleteUsers(idsArr);
        } catch (Exception e) {
            logger.error("",e);
            map.put("success",false);
            map.put("msg","删除用户失败！");
        }
        try {
            ResponseUtils.outPut(response,map);
        } catch (Exception e) {
            logger.error("",e);
        }
    }

    /**
     * 查询用户信息
     */
    @RequestMapping("/listUserInfo")
    public void listUserInfo(HttpServletRequest request,HttpServletResponse response){
        UserInfoPo u=createUserInfo(request);
        String pageNo=request.getParameter("page");
        String pageSize=request.getParameter("limit");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("success",true);
        map.put("msg","查询用户信息成功！");
        try {
            List<UserInfoPo> userList;
            if (!StringUtils.isEmpty(pageNo) && !StringUtils.isEmpty(pageSize)){
                userList=userInfoService.
                        listUserInfo(u,Integer.parseInt(pageNo),Integer.parseInt(pageSize));
            }else {
                userList=userInfoService.listUserInfo(u);
            }
            int total=userInfoService.getTotal(u);
            map.put("userInfoList",userList);
            map.put("total",total);
        } catch (Exception e) {
            logger.error("",e);
            map.put("success",false);
            map.put("msg","查询用户信息失败！");
        }
        try {
            ResponseUtils.outPut(response,map);
        } catch (Exception e) {
            logger.error("",e);
        }


    }


    /**
     * 将前段请求字段转化为userInfoPo对象
     */
    private UserInfoPo createUserInfo(HttpServletRequest request){
        UserInfoPo po=new UserInfoPo();
        po.setId(request.getParameter("id"));
        po.setUserName(request.getParameter("userName"));
        if(!StringUtils.isEmpty(request.getParameter("password"))){
            po.setPassword(CryptographyUtil.md5(request.getParameter("password"),"fesine"));
        }
        po.setSex(request.getParameter("sex"));
        po.setNickName(request.getParameter("nickName"));
        po.setCellPhone(request.getParameter("cellPhone"));
        po.setAdress(request.getParameter("address"));
        po.setHeadPhoto(request.getParameter("headPhoto"));
        po.setInfoDesc(request.getParameter("infoDesc"));
        return po;

    }

    /**
     * 上传头像
     */
    private String uploadPhotos(MultipartFile photos,HttpServletRequest request) throws IOException {
        String headPhoto;
        String fileName= DateUtils.formatDate(new Date(),"yyyyMMddHHmmssss");
        String root=ResponseUtils.getRootPath(request);
        String filePath=root+uploadFileRoot;
        String orgFileName=photos.getOriginalFilename();
        String fileType=orgFileName.substring(orgFileName.lastIndexOf(".")+1);
        fileName="["+fileType+"]"+fileName+"."+fileType;
        filePath=filePath+fileName;
        logger.info("------------->上传文件路径："+filePath);
        long startTime=System.currentTimeMillis();//获取开始时间
        try {
            //执行上传
            photos.transferTo(new File(filePath));
            headPhoto=fileName;
            long endTime=System.currentTimeMillis();//结束时间
            logger.info("上传文件共用时："+(startTime-endTime)+"毫秒");
            return headPhoto;
        } catch (IOException e) {
            logger.info("上传头像失败",e);
            throw e;
        }

    }
}
